package com.tarena.lbs.basic.web.repository;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.protocol.pager.BasePageList;
import com.tarena.lbs.basic.web.mapper.BusinessMapper;
import com.tarena.lbs.pojo.basic.bo.BusinessBO;
import com.tarena.lbs.pojo.basic.dos.BusinessDO;
import com.tarena.lbs.pojo.basic.po.BusinessPO;
import com.tarena.lbs.pojo.basic.query.BusinessQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
@Slf4j
@Repository
public class BusinessRepository {
    @Autowired
    private BusinessMapper businessMapper;
    public BasePageList<BusinessBO> getBusinessListByQuery(BusinessQuery businessQuery) {
        log.info("查询商家列表的入参:{}",businessQuery);
        //1.开启pageHelper 查询动作 必须在开启之后执行,中间不能有任何其他的业务代码
        PageHelper.startPage(businessQuery.getPageNo(),businessQuery.getPageSize());
        List<BusinessDO> dos = businessMapper.selectBusinessByQuery(businessQuery);
        //2.使用pagehelper拿到tatal和转化
        PageInfo<BusinessDO> pageDOS = new PageInfo<>(dos);
        //3.封装一个BasePageList 需要转化
        List<BusinessBO> bos = new ArrayList<>();
        if (pageDOS.getTotal()!=0){
            dos.stream().forEach(bDo->{
                BusinessBO bo = new BusinessBO();
                BeanUtils.copyProperties(bDo,bo);
                bos.add(bo);
            });
        }
        return new BasePageList<>(bos,pageDOS.getTotal());

    }

    public void save(BusinessBO businessBO) {
        //1.仓储层 BO 转化成DO
        BusinessDO businessDO = new BusinessDO();
        BeanUtils.copyProperties(businessBO,businessDO);
        //2.新增
        businessMapper.insert(businessDO);
    }

    public long countBusinessById(Integer businessId) {
        return businessMapper.selectCountById(businessId);
    }

    public BusinessPO getBusiness(Integer id) {
        return businessMapper.selectById(id);
    }
}
